package com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.xiaoxing.zhinenghuacangku_nanjinglu.R;
import com.xiaoxing.zhinenghuacangku_nanjinglu.R2;
import com.xiaoxing.zhinenghuacangku_nanjinglu.di.component.DaggerNanJingLu_ReturnLibraryComponent;
import com.xiaoxing.zhinenghuacangku_nanjinglu.di.module.NanJingLu_ReturnLibraryModule;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.contract.NanJingLu_ReturnLibraryContract;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.model.entity.GetUserSpaceListForAutoStore;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.presenter.NanJingLu_ReturnLibraryPresenter;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ZHI_NENG_HUA_CANG_KU_NanJingLu_RETURN_LIBRARY_ACTIVITY)
public class NanJingLu_ReturnLibraryActivity extends BaseActivity
        <NanJingLu_ReturnLibraryPresenter> implements NanJingLu_ReturnLibraryContract.View, EasyPermissions.PermissionCallbacks {

    public static final int REQUEST_WU_LIAO = 101;
    public static final int REQUEST_HUAN_CHONG_WEI = 102;
    public static final String INSTORE_BUFFER_ID = "instoreBufferId";
    public static final String MID = "mid";
    public static final String IS_RETURN_GET_MATERIAL_PLATE_SUCCESS = "isReturnGetMaterialPlateSuccess";
    public static final String IS_CAN_RETURN = "isCanReturn";
    public static final String IS_XUAN_ZE_XIN_CANG_WEI = "is_Xuan_ze_xin_cang_wei";
    private static Disposable mDisposable;
    @BindView(R2.id.btn_scan_wu_liao)
    Button btnScanWuLiao;
    @BindView(R2.id.et_num)
    EditText etNum;
    @BindView(R2.id.btn_scan_qr_code)
    Button btnScanQrCode;
    @BindView(R2.id.btn_confirm_return_library)
    Button btnConfirmReturnLibrary;
    @BindView(R2.id.tv_agv_huan_chong_wei)
    TextView tvAgvHuanChongWei;
    @BindView(R2.id.tv_wu_liao_name)
    TextView tv_wu_liao_name;
    @BindView(R2.id.btn_que_ding_qu_tuo_pan)
    Button mBtnQueDingQuTuoPan;
    @BindView(R2.id.btn_quxiao_return_library)
    Button btn_quxiao_return_library;

    @BindView(R2.id.et_weizhi)
    EditText etWeizhi;
    @BindView(R2.id.tv_check)
    TextView tvCheck;
    @BindView(R2.id.nice_position)
    NiceSpinner spPosition;
    @BindView(R2.id.ll_cang_wei)
    LinearLayout ll_cang_wei;
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private String mid; //物料id
    private String instoreBufferId; //缓冲位置id
    private String isCanReturn = "0";//是否可以退库
    private boolean isReturnGetMaterialPlateSuccess = false; //取托盘是否成功
    private int spid = 0;
    private String spname = "";
    private String cangWeiPosition = "";

    @OnClick(R2.id.tv_check)
    public void cangWeiChaXun() {
//        if (TextUtils.isEmpty(getCangWei())) {
//            ArmsUtils.makeText(this, "请输入仓位的名称");
//            return;
//        }
        getUserSpaceListForAutoStore(getCangWei());

    }

    /**
     * 查询仓位
     *
     * @param spname
     */
    private void getUserSpaceListForAutoStore(String spname) {
//        mPresenter.getUserSpaceListForAutoStore(this, mSharedPreferencesHelper.getString(BaseConstants.UID), spname);
        getUserSpaceListForAutoStore(mSharedPreferencesHelper.getString(BaseConstants.UID), spname);
    }

    private String getCangWei() {
        return etWeizhi.getText().toString().trim();
    }

    private void getUserSpaceListForAutoStore(String user_id, String spname) {

        showLoading();
        String methodName = "GetUserSpaceListForAutoStore";
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("spname", spname);
        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    List<GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList = ArmsUtils.parseString2List(result, GetUserSpaceListForAutoStore.class);
                    initSpPosition(getUserSpaceListForAutoStoreList);

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    /**
     * 初始化缓冲位列表下拉选
     */
    private void initSpPosition(List<GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList) {
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < getUserSpaceListForAutoStoreList.size(); i++) {
            list.add(String.valueOf(
                    new StringBuilder()
                            .append(getUserSpaceListForAutoStoreList.get(i).getSpname())
            ));
        }
        spid = getUserSpaceListForAutoStoreList.get(0).getSpid();
        spname = list.get(0);
        cangWeiPosition = String.valueOf(getUserSpaceListForAutoStoreList.get(0).getSpid());
        spPosition.attachDataSource(list);
        spPosition.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                cangWeiPosition = String.valueOf(getUserSpaceListForAutoStoreList.get(position).getSpid());
                spid = getUserSpaceListForAutoStoreList.get(position).getSpid();
                spname = getUserSpaceListForAutoStoreList.get(position).getSpname();
            }
        });
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(getContext(), message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null)
            mDisposable.dispose();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");

    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerNanJingLu_ReturnLibraryComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .nanJingLu_ReturnLibraryModule(new NanJingLu_ReturnLibraryModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.zhi_neng_cang_ku_nan_jing_lu_activity_return_library_lin_yi; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, "退库");

        btnScanWuLiao.setEnabled(true);
        btnScanQrCode.setEnabled(false);
        mBtnQueDingQuTuoPan.setEnabled(false);
        btnConfirmReturnLibrary.setEnabled(false);
        btn_quxiao_return_library.setEnabled(true);
        btn_quxiao_return_library.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));

        if (!TextUtils.isEmpty(mSharedPreferencesHelper.getString(MID))) {

            btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnScanWuLiao.setEnabled(false);
            btn_quxiao_return_library.setEnabled(true);
            btn_quxiao_return_library.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
            if (mSharedPreferencesHelper.getBoolean(IS_XUAN_ZE_XIN_CANG_WEI)) {
                ll_cang_wei.setVisibility(View.VISIBLE);
                mBtnQueDingQuTuoPan.setVisibility(View.GONE);
            } else {
                ll_cang_wei.setVisibility(View.GONE);
                mBtnQueDingQuTuoPan.setVisibility(View.VISIBLE);
                mBtnQueDingQuTuoPan.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                mBtnQueDingQuTuoPan.setEnabled(true);
            }

            btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
            btnScanQrCode.setEnabled(true);

            if (!TextUtils.isEmpty(mSharedPreferencesHelper.getString(INSTORE_BUFFER_ID))) {
                btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                btnScanQrCode.setEnabled(false);
                btn_quxiao_return_library.setEnabled(false);
                btn_quxiao_return_library.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));

                if (mSharedPreferencesHelper.getBoolean(IS_RETURN_GET_MATERIAL_PLATE_SUCCESS)) {
                    mBtnQueDingQuTuoPan.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    mBtnQueDingQuTuoPan.setEnabled(false);

                    if (mSharedPreferencesHelper.getString(IS_CAN_RETURN).equals("1")) {
                        isCanReturn = "1";
                        btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                        btnConfirmReturnLibrary.setEnabled(true);
                    }
                }
            }
        }
//        btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
//        btnConfirmReturnLibrary.setEnabled(true);

        intervalTransfered();
    }

    private void intervalTransfered() {

        Observable.interval(30, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable disposable) {
                        mDisposable = disposable;
                    }

                    @Override
                    public void onNext(@NonNull Long number) {
//                        if (!TextUtils.isEmpty(mSharedPreferencesHelper.getString(MID)) && !TextUtils.isEmpty(mSharedPreferencesHelper.getString(INSTORE_BUFFER_ID)) && mSharedPreferencesHelper.getBoolean(IS_RETURN_GET_MATERIAL_PLATE_SUCCESS) && mPresenter != null)
//                            mPresenter.CheckCanReturnInstoreBuffer(ReturnLibraryActivity.this, mSharedPreferencesHelper.getString(MID));
                        CheckCanReturnInstoreBuffer(mSharedPreferencesHelper.getString(MID));
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    /**
     * 确认是否可以退库(退库时轮询此函数，当返回true 则可以调用ReturnInstore)
     * 1 可以调用 0 不可以调用
     *
     * @param mid
     * @return
     */
    private void CheckCanReturnInstoreBuffer(String mid) {
        showLoading();

        String methodName = "CheckCanReturnInstoreBuffer";
        SoapParams params = new SoapParams();
        params.put("mid", mid);
        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    isCanReturn = result;

                    if (isCanReturn.equals("1")) {
                        mSharedPreferencesHelper.putString(IS_CAN_RETURN, "1");
                        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        mBtnQueDingQuTuoPan.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                        btnScanQrCode.setEnabled(false);
                        btnScanWuLiao.setEnabled(false);
                        mBtnQueDingQuTuoPan.setEnabled(false);
                        btnConfirmReturnLibrary.setEnabled(true);
                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @OnClick({R2.id.btn_scan_wu_liao, R2.id.btn_scan_qr_code, R2.id.btn_confirm_return_library, R2.id.btn_que_ding_qu_tuo_pan, R2.id.btn_quxiao_return_library})
    public void onViewClicked(View view) {
        if (!getPermission()) return;
        int i = view.getId();
        if (i == R.id.btn_scan_wu_liao) {
            Intent newIntent = new Intent(this, NanJingLu_ScanQRCodeActivity.class);
            mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, REQUEST_WU_LIAO);
            startActivityForResult(newIntent, REQUEST_WU_LIAO);
        } else if (i == R.id.btn_scan_qr_code) {
            Intent newIntent = new Intent(this, NanJingLu_ScanQRCodeActivity.class);
            mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, REQUEST_HUAN_CHONG_WEI);
            startActivityForResult(newIntent, REQUEST_HUAN_CHONG_WEI);
        } else if (i == R.id.btn_que_ding_qu_tuo_pan) {
            if (TextUtils.isEmpty(getNum())) {
                ArmsUtils.makeText(this, "请填写数量");
                return;
            }
//            mPresenter.ReturnGetMaterialPlate(this, mid, instoreBufferId, mSharedPreferencesHelper.getString(BaseConstants.UID));
            ReturnGetMaterialPlate(mid, instoreBufferId, mSharedPreferencesHelper.getString(BaseConstants.UID));
        } else if (i == R.id.btn_quxiao_return_library) {
            clearDataInit();
        } else if (i == R.id.btn_confirm_return_library) {

            if (mSharedPreferencesHelper.getBoolean(IS_XUAN_ZE_XIN_CANG_WEI)) {
                if (spid > 0) {
                    if (TextUtils.isEmpty(getNum())) {
                        ArmsUtils.makeText(this, "请填写数量");
                        return;
                    }
//                    mPresenter.AddAgvTaskInstore(this, mSharedPreferencesHelper.getString(MID), mSharedPreferencesHelper.getString(INSTORE_BUFFER_ID), String.valueOf(spid), getNum(), mSharedPreferencesHelper.getString(BaseConstants.UID));
                    AddAgvTaskInstore(mSharedPreferencesHelper.getString(MID), mSharedPreferencesHelper.getString(INSTORE_BUFFER_ID), String.valueOf(spid), getNum(), mSharedPreferencesHelper.getString(BaseConstants.UID));
                } else {
                    ArmsUtils.makeText(this, "请选择仓位");
                }
                return;
            }

            if (isCanReturn.equals("1")) {

                if (TextUtils.isEmpty(mSharedPreferencesHelper.getString(MID))) {
                    ArmsUtils.makeText(this, "请先扫描物料二维码");
                    return;
                }
                if (TextUtils.isEmpty(getNum())) {
                    ArmsUtils.makeText(this, "请填写数量");
                    return;
                }
                if (TextUtils.isEmpty(mSharedPreferencesHelper.getString(INSTORE_BUFFER_ID))) {
                    ArmsUtils.makeText(this, "请扫描缓冲位");
                    return;
                }

//                mPresenter.returnInstore(this, mSharedPreferencesHelper.getString(MID), mSharedPreferencesHelper.getString(INSTORE_BUFFER_ID), mSharedPreferencesHelper.getString(BaseConstants.UID), getNum());
                returnInstore(mSharedPreferencesHelper.getString(MID), mSharedPreferencesHelper.getString(INSTORE_BUFFER_ID), mSharedPreferencesHelper.getString(BaseConstants.UID), getNum());

            } else {
                ArmsUtils.makeText(NanJingLu_ReturnLibraryActivity.this, "不可以退库");
            }

        }
    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的照相使用权限", 103, permissions);
            return false;
        }

    }

    @NonNull
    private String getNum() {
        return etNum.getText().toString().trim();
    }

    /**
     * 退库的时候   先去拿仓位上的托盘
     *
     * @param mid
     * @param instoreBufferId
     * @param uid
     * @return
     */
    private void ReturnGetMaterialPlate(String mid, String instoreBufferId, String uid) {

        showLoading();
        String methodName = "ReturnGetMaterialPlate";
        SoapParams params = new SoapParams();
        params.put("mid", mid);
        params.put("instoreBufferId", instoreBufferId);
        params.put("uid", uid);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    if (!result.equals("-1")) {
                        btn_quxiao_return_library.setEnabled(false);
                        btn_quxiao_return_library.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));

                        isReturnGetMaterialPlateSuccess = true;
                        mSharedPreferencesHelper.putBoolean(IS_RETURN_GET_MATERIAL_PLATE_SUCCESS, true);
                        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        mBtnQueDingQuTuoPan.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanQrCode.setEnabled(false);
                        btnScanWuLiao.setEnabled(false);
                        mBtnQueDingQuTuoPan.setEnabled(false);
                        btnConfirmReturnLibrary.setEnabled(false);

                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void clearDataInit() {
        etNum.setText("");
        mid = "";
        instoreBufferId = "";
        isReturnGetMaterialPlateSuccess = false;
        tv_wu_liao_name.setVisibility(View.GONE);
        tv_wu_liao_name.setText("");
        tvAgvHuanChongWei.setVisibility(View.GONE);
        tvAgvHuanChongWei.setText("");
        mSharedPreferencesHelper.putBoolean(IS_RETURN_GET_MATERIAL_PLATE_SUCCESS, false);
        mSharedPreferencesHelper.putString(INSTORE_BUFFER_ID, "");
        mSharedPreferencesHelper.putString(MID, "");
        mSharedPreferencesHelper.putString(IS_CAN_RETURN, "");

        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
        btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
        mBtnQueDingQuTuoPan.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
        btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
        btnScanQrCode.setEnabled(false);
        btnScanWuLiao.setEnabled(true);
        mBtnQueDingQuTuoPan.setEnabled(false);
        btnConfirmReturnLibrary.setEnabled(false);
    }

    /**
     * 退库的时候扫描物料二维码，如果仓位托盘不存在，显示选择仓位
     *
     * @param mid
     * @param instoreBufferId
     * @param spid
     * @param num
     * @param uid
     * @return
     */
    private void AddAgvTaskInstore(String mid, String instoreBufferId, String spid, String num, String uid) {

        showLoading();
        String methodName = "AddAgvTaskInstore";
        SoapParams params = new SoapParams();
        params.put("mid", mid);
        params.put("instoreBufferId", instoreBufferId);
        params.put("spid", spid);
        params.put("num", num);
        params.put("uid", uid);


        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    clearDataInit();

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * 退库
     *
     * @param mid
     * @param instoreBufferId
     * @param uid
     * @param num
     * @return
     */
    private void returnInstore(String mid, String instoreBufferId, String uid, String num) {
        showLoading();

        String methodName = "ReturnInstore";
        SoapParams params = new SoapParams();
        params.put("mid", mid);
        params.put("instoreBufferId", instoreBufferId);
        params.put("uid", uid);
        params.put("num", num);


        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    clearDataInit();

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == REQUEST_WU_LIAO) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                mid = extras.getString(BaseConstants.SCAN_RESULT);
//                mPresenter.validateReturnInstore(this, mid);
                validateReturnInstore(mid);
            }

        } else if (resultCode == REQUEST_HUAN_CHONG_WEI) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                instoreBufferId = extras.getString(BaseConstants.SCAN_RESULT);
//                mPresenter.setInstoreBufferReadyForAGV(this, instoreBufferId, spname);
                setInstoreBufferReadyForAGV(instoreBufferId, spname);
            }
        }
    }

    /**
     * 验证物料二维码的有效性
     *
     * @param mid
     * @return
     */
    private void validateReturnInstore(String mid) {

        showLoading();
        String methodName = "ValidateReturnInstore";
        SoapParams params = new SoapParams();
        params.put("mid", mid);


        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    if (!TextUtils.isEmpty(result) && !result.equals("0")) {
                        spname = result;
                        ll_cang_wei.setVisibility(View.GONE);
                        mBtnQueDingQuTuoPan.setVisibility(View.VISIBLE);
                        mSharedPreferencesHelper.putBoolean(IS_XUAN_ZE_XIN_CANG_WEI, false);

                        tv_wu_liao_name.setVisibility(View.VISIBLE);
                        tv_wu_liao_name.setText(result);

                        mSharedPreferencesHelper.putString(MID, mid);

                        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                        btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        mBtnQueDingQuTuoPan.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanQrCode.setEnabled(true);
                        btnScanWuLiao.setEnabled(false);
                        mBtnQueDingQuTuoPan.setEnabled(false);
                        btnConfirmReturnLibrary.setEnabled(false);
                        btn_quxiao_return_library.setEnabled(true);
                        btn_quxiao_return_library.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));

                    } else {
                        mSharedPreferencesHelper.putString(MID, mid);
                        ll_cang_wei.setVisibility(View.VISIBLE);
                        mBtnQueDingQuTuoPan.setVisibility(View.GONE);
                        mSharedPreferencesHelper.putBoolean(IS_XUAN_ZE_XIN_CANG_WEI, true);
                        btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanWuLiao.setEnabled(false);
                        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                        btnScanQrCode.setEnabled(true);
                        btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnConfirmReturnLibrary.setEnabled(false);
                        btn_quxiao_return_library.setEnabled(true);
                        btn_quxiao_return_library.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));

                    }

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * 入库 扫描入库缓冲位二维码,调用此方法,传入二维码里的id,将此缓冲位置满,如果设置成功,返回true
     * 设置失败 返回false,失败的原因有：1.此缓冲位已占满 2.此缓冲位没有启用 3.此缓冲位是出库缓冲位(标签贴错)
     *
     * @param bufferId
     * @return
     */
    private void setInstoreBufferReadyForAGV(String bufferId, String spname) {
        showLoading();

        String methodName = "SetInstoreBufferReadyForAGV";
        SoapParams params = new SoapParams();
        params.put("bufferId", bufferId);
        params.put("spname", spname);


        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    LogUtils.debugInfo("setInstoreBufferReadyForAGV=" + result);
                    if (result.equals("false")) {
                        ArmsUtils.makeText(getContext(), "缓冲位置不可用，请联系管理员");
                    } else {
                        btn_quxiao_return_library.setEnabled(true);
                        btn_quxiao_return_library.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));

                        mSharedPreferencesHelper.putString(INSTORE_BUFFER_ID, instoreBufferId);

                        tvAgvHuanChongWei.setVisibility(View.VISIBLE);
                        tvAgvHuanChongWei.setText(new StringBuilder().append("已选择的Agv缓冲位置：").append(instoreBufferId));

                        if (mSharedPreferencesHelper.getBoolean(IS_XUAN_ZE_XIN_CANG_WEI)) {

                            mBtnQueDingQuTuoPan.setVisibility(View.GONE);

                            btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                            btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                            btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                            btnScanQrCode.setEnabled(false);
                            btnScanWuLiao.setEnabled(false);
                            btnConfirmReturnLibrary.setEnabled(true);

                        } else {
                            btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                            btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                            mBtnQueDingQuTuoPan.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                            btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                            btnScanQrCode.setEnabled(false);
                            btnScanWuLiao.setEnabled(false);
                            mBtnQueDingQuTuoPan.setEnabled(true);
                            btnConfirmReturnLibrary.setEnabled(false);

                        }


                    }

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == 103) {
        }
    }

    @Override
    public void validateReturnInstoreSuccess(String validateReturnInstore) {

        if (!TextUtils.isEmpty(validateReturnInstore) && !validateReturnInstore.equals("0")) {
            spname = validateReturnInstore;
            ll_cang_wei.setVisibility(View.GONE);
            mBtnQueDingQuTuoPan.setVisibility(View.VISIBLE);
            mSharedPreferencesHelper.putBoolean(IS_XUAN_ZE_XIN_CANG_WEI, false);

            tv_wu_liao_name.setVisibility(View.VISIBLE);
            tv_wu_liao_name.setText(validateReturnInstore);

            mSharedPreferencesHelper.putString(MID, mid);

            btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
            btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            mBtnQueDingQuTuoPan.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnScanQrCode.setEnabled(true);
            btnScanWuLiao.setEnabled(false);
            mBtnQueDingQuTuoPan.setEnabled(false);
            btnConfirmReturnLibrary.setEnabled(false);
            btn_quxiao_return_library.setEnabled(true);
            btn_quxiao_return_library.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));

        } else {
            mSharedPreferencesHelper.putString(MID, mid);
            ll_cang_wei.setVisibility(View.VISIBLE);
            mBtnQueDingQuTuoPan.setVisibility(View.GONE);
            mSharedPreferencesHelper.putBoolean(IS_XUAN_ZE_XIN_CANG_WEI, true);
            btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnScanWuLiao.setEnabled(false);
            btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
            btnScanQrCode.setEnabled(true);
            btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnConfirmReturnLibrary.setEnabled(false);
            btn_quxiao_return_library.setEnabled(true);
            btn_quxiao_return_library.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));

        }
    }

    @Override
    public void setInstoreBufferReadyForAGVSuccess(String setInstoreBufferReadyForAGV) {
        LogUtils.debugInfo("setInstoreBufferReadyForAGV=" + setInstoreBufferReadyForAGV);
        if (setInstoreBufferReadyForAGV.equals("false")) {
            ArmsUtils.makeText(this, "缓冲位置不可用，请联系管理员");
        } else {
            btn_quxiao_return_library.setEnabled(true);
            btn_quxiao_return_library.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));

            mSharedPreferencesHelper.putString(INSTORE_BUFFER_ID, instoreBufferId);

            tvAgvHuanChongWei.setVisibility(View.VISIBLE);
            tvAgvHuanChongWei.setText(new StringBuilder().append("已选择的Agv缓冲位置：").append(instoreBufferId));

            if (mSharedPreferencesHelper.getBoolean(IS_XUAN_ZE_XIN_CANG_WEI)) {

                mBtnQueDingQuTuoPan.setVisibility(View.GONE);

                btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                btnScanQrCode.setEnabled(false);
                btnScanWuLiao.setEnabled(false);
                btnConfirmReturnLibrary.setEnabled(true);

            } else {
                btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                mBtnQueDingQuTuoPan.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                btnScanQrCode.setEnabled(false);
                btnScanWuLiao.setEnabled(false);
                mBtnQueDingQuTuoPan.setEnabled(true);
                btnConfirmReturnLibrary.setEnabled(false);

            }


        }
    }

    @Override
    public void returnInstoreSuccess(String returnInstore) {
        clearDataInit();
    }

    @Override
    public void ReturnGetMaterialPlateSuccess(String returnGetMaterialPlate) {

        if (!returnGetMaterialPlate.equals("-1")) {
            btn_quxiao_return_library.setEnabled(false);
            btn_quxiao_return_library.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));

            isReturnGetMaterialPlateSuccess = true;
            mSharedPreferencesHelper.putBoolean(IS_RETURN_GET_MATERIAL_PLATE_SUCCESS, true);
            btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            mBtnQueDingQuTuoPan.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnScanQrCode.setEnabled(false);
            btnScanWuLiao.setEnabled(false);
            mBtnQueDingQuTuoPan.setEnabled(false);
            btnConfirmReturnLibrary.setEnabled(false);

        }
    }

    @Override
    public void CheckCanReturnInstoreBufferSuccess(String checkCanReturnInstoreBuffer) {

        isCanReturn = checkCanReturnInstoreBuffer;

        if (isCanReturn.equals("1")) {
            mSharedPreferencesHelper.putString(IS_CAN_RETURN, "1");
            btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnScanWuLiao.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            mBtnQueDingQuTuoPan.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnConfirmReturnLibrary.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
            btnScanQrCode.setEnabled(false);
            btnScanWuLiao.setEnabled(false);
            mBtnQueDingQuTuoPan.setEnabled(false);
            btnConfirmReturnLibrary.setEnabled(true);
        }
    }

    @Override
    public void AddAgvTaskInstoreSuccess(String addAgvTaskInstore) {
        clearDataInit();
    }

    @Override
    public void getUserSpaceListForAutoStoreSuccess(List<GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList) {
        initSpPosition(getUserSpaceListForAutoStoreList);
    }
}
